using System;
using System.Runtime.InteropServices;

namespace FileUtility.FTP.FtpSupport
{
	/// <summary>
	/// Summary description for FtpException.
	/// </summary>
	public class FtpException : ApplicationException
	{
		private int errorCode;

		internal FtpException(string message, int lastError) : base(message)
		{
			errorCode = lastError;
		}

		public int ErrorCode
		{
			get { return errorCode; }
		}

		internal static void THROWONFALSE(bool rc)
		{
			if(!rc)
			{
				throw GetFtpException();
			}
		}

		internal static void THROWONNULL(IntPtr handle)
		{
			if(handle == IntPtr.Zero)
			{
				throw GetFtpException();
			}
		}

		public static FtpException GetFtpException()
		{
			int lastError = Marshal.GetLastWin32Error();
			string message = null;
			if(lastError == NativeMethods.ERROR_INTERNET_EXTENDED_ERROR)
			{
				NativeMethods.InternetGetLastResponseInfo(out message);
			}
			else if(lastError >= NativeMethods.INTERNET_ERROR_FIRST && lastError <= NativeMethods.INTERNET_ERROR_LAST)
			{
				//Get the error message for these errors
				message = String.Format("TODO: INTERNET_ERROR_* need message mappings {0}", lastError);
				//NativeMethods.InternetGetLastResponseInfo(out message);
			}
			else
			{
				message = new System.ComponentModel.Win32Exception(lastError).Message;
			}

			return new FtpException(message, lastError);
		}
	}
}
